﻿using System;
using System.Collections.Generic;
using System.Text;
using WebSocket4Net;

namespace Client
{
    public class WebSocketHelper
    {
        public readonly static WebSocketHelper Instance = new WebSocketHelper();
        private WebSocket websocket;

        //声明一个委托
        public delegate void MessageEventHandler(object sender, MessageEventArgs e);
        //声明一个事件
        public event MessageEventHandler MessageResult;


        private WebSocketHelper()
        {
        }


        public int Start(string sIP,string sPort)
        {
            websocket = new WebSocket("ws://" + sIP.Trim() + ":" + sPort.Trim());
            websocket.Opened += websocket_Opened;
            websocket.Closed += websocket_Closed;
            websocket.MessageReceived += websocket_MessageReceived;
            websocket.Open();

            return 1;
        }

        public void Send(string sMessage)
        {
            websocket.Send(sMessage);
        }

        private void websocket_Closed(object sender, EventArgs e)
        {
            websocket.Send("一个客户端 下线");
        }

        void websocket_Opened(object sender, EventArgs e)
        {
            websocket.Send("一个客户端 上线");
        }

        private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            //this.listBox1.Invoke(new EventHandler(ShowMessage), e.Message);
            var args = new MessageEventArgs(e.Message);
            MessageResult(this, args);
        }
    }

    public class MessageEventArgs : System.EventArgs
    {
        private string mResult;

        public MessageEventArgs(string sResult)
        {
            this.mResult = sResult;
        }
        public string Result { get { return mResult; } }
    }

}
